/*
 *  下面这个类虽然实现了 Iterator 接口，但不理想，因为每个实例只能被迭代一次
 *  实例可以迭代 limit 次
 */
class OnceCounter {
  constructor (limit) {
    this.count = 1;
    this.limit = limit;
  }

  next () {
    if (this.count <= this.limit) {
      return { done: false, value: this.count++ };
    } else {
      return { done: true, value: undefined };
    }
  }

  [Symbol.iterator] () {
    return this;
  }
}

let onceCounter = new OnceCounter(3);

for (let i of onceCounter) {
  console.log('onceCounter first: ', i)
}
for (let i of onceCounter) {
  console.log('onceCounter second', i)  // 没有打印结果
}

/*
 *  下面这个类把计数器变量放到闭包里，然后通过闭包返回迭代器，这样一个实例就能够创建多个迭代器
 */
class Counter {
  constructor (limit) {
    this.limit = limit;
  }

  [Symbol.iterator] () {
    let count = 1,
        limit = this.limit;
    return {
      next () {
        if (count <= limit) {
          return { done: false, value: count++ };
        } else {
          return { done: true, value: undefined };
        }
      }
    };
  }
}

let counter = new Counter(3);

for (let i of counter) {
  console.log('counter first: ', i);
}
for (let i of counter) {
  console.log('counter second: ', i);
}